import {getStorageItem, setStorageItem} from '../../../utils/storage';
import {
  getUserInfo,
  getCaseList,
  addBrowses,
  getUserComments,
} from '../../../api/weddingMan/index';
const app = getApp();
const NAVLIST = [
  {
    id: 0,
    name: '作品',
  },
  {
    id: 1,
    name: '评价',
  },
];
Page({
  data: {
    navList: NAVLIST,
    activeNavId: 0,
    caseList: [],
    commentList: [],
    isPlay: true,
    homeCarouseList: [],
    userType: '',
    avator: '',
    browses: 0,
    name: '',
    description: '',
    city: '',
    phone: '',
    wechat: '',
    pHeight: '',
    pWeight: '',
    pYear: '',
    birthday: '',
    userId: '',
    team_name: '',
    shareType: '2',
    infoPopupVisible: false,
    caseLen: 0,
    commentsLen: 0,
    playIconVisible: true
  },
  onLoad: function(options) {
    ;
    if (options.id) {
      this.setData({
        userId: options.id,
        shareType: options.type,
      });
      setStorageItem('hlrUserId', options.id);
      setStorageItem('hlrShareType', options.type);
    } else if (options.scene) {
      this.setData({
        userId: options.scene,
        shareType: '2',
      });
      setStorageItem('hlrUserId', options.id);
      setStorageItem('hlrShareType', options.type);
    } else {
      const HLRUSERID = '278da07144af46e599b5546b2b75535e';
      const storageUserId = getStorageItem('hlrUserId');
      if (storageUserId) {
        this.setData({
          userId: storageUserId,
          shareType: getStorageItem('hlrShareType'),
        });
      } else {
        // 缓存中从未有过hlrUserId使用默认的hlrUserId
        setStorageItem('hlrUserId', HLRUSERID);
        setStorageItem('hlrShareType', '2');
        this.setData({
          userId: HLRUSERID,
          shareType: '2',
        });
      }
    }
    const storageToken = getStorageItem('token');
    if (storageToken) {
      this.initData();
    } else {
      this.initDataThis = this.initData.bind(this);
      app.observe(app.globalData, 'tokenForAuth', {
        watchKey: 'tokenForAuth',
        watch: this.initDataThis
      });
    }
  },
  onShareAppMessage: function() {
    return {
      title: `${this.data.name}的主页`,
      path:
        'pages/weddingMan/personal/personal?id=' +
        this.data.userId +
        '&type=' +
        this.data.shareType,
    };
  },
  onShow: function() {
    wx.hideHomeButton()
    if (this.data.userId) {
      addBrowses({
        userId: this.data.userId,
      })
        .then(res => {
          console.log(res);
        })
        .catch(err => {
          console.log(err);
        });
    }
    if (app.globalData.needRefreshCaseList === '1') {
      getCaseList(this.data.userId)
        .then(res => {
          console.log(res);
          this.setData({
            caseList: res.data.list,
            caseLen: Number(res.data.totalResult),
          });
          app.globalData.needRefreshCaseList = '0';
        })
        .catch(err => {
          console.log(err);
        });
    }

    this.setData({
      playIconVisible: true
    })
    setTimeout(() => {
      this.setData({
        playIconVisible: false
      })
    }, 3000);
  },
  onUnload: function() {
    if(this.initDataThis) {
      app.unObserve('tokenForAuth', this.initDataThis);
    }
  },
  updated() {
    this.initData();
  },
  handleInfoPopupClose() {
    this.setData({
      infoPopupVisible: false,
    });
  },
  chooseNav(e) {
    console.log(e);
    this.setData({
      activeNavId: e.currentTarget.dataset.id,
    });
  },
  initData() {
    getUserInfo(this.data.userId, getStorageItem('hlrUserType'))
      .then(res => {
        console.log(res);
        this.setData({
          avator: res.data.user_headimg,
          name: res.data.user_qm_name,
          homeCarouseList: this.getHomeCarouseList(res.data.user_lbt),
          userType: this.getUserType(res.data.user_type),
          browses: res.data.browses || '0',
          description: res.data.user_desc,
          city: res.data.user_city,
          phone: res.data.phonenumber,
          wechat: res.data.user_wx,
          pHeight: res.data.user_height,
          pWeight: res.data.user_weight,
          birthday: res.data.uesr_birthday,
          pYear: res.data.user_age,
        });
        if (res.data.teamInfo) {
          this.setData({
            team_name: res.data.teamInfo.team_name,
          });
        }
        wx.setNavigationBarTitle({
          title: `${this.data.name}的主页`,
        });
      })
      .catch(err => {
        console.log(err);
      });
    getCaseList(this.data.userId)
      .then(res => {
        console.log(res);
        this.setData({
          caseList: res.data.list,
          caseLen: Number(res.data.totalResult),
        });
      })
      .catch(err => {
        console.log(err);
      });
    getUserComments({
      userId: this.data.userId,
      currentPage: 1,
      showCount: 20,
    })
      .then(res => {
        console.log(res);
        this.setData({
          commentList: res.data.list,
          commentsLen: Number(res.data.totalResult),
        });
      })
      .catch(err => {
        console.log(err);
      });
  },
  getHomeCarouseList(pLbt) {
    let tmpArr = [];
    if (pLbt) {
      try {
        tmpArr = JSON.parse(pLbt);
      } catch (err) {
        console.log(err);
      }
    }
    return tmpArr;
  },
  getUserType(pType) {
    const OCCUPATION = [
      {
        id: '1',
        name: '主持人',
      },
      {
        id: '2',
        name: '摄像师',
      },
      {
        id: '3',
        name: '摄影师',
      },
      {
        id: '4',
        name: '化妆师',
      },
      {
        id: '5',
        name: '婚礼机构',
      },
    ];
    const tmpIndex = OCCUPATION.findIndex(
      item => parseInt(item.id, 10) === parseInt(pType, 10),
    );
    let ocp = '主持人';
    if (OCCUPATION[tmpIndex]) {
      ocp = OCCUPATION[tmpIndex].name;
    }
    return ocp;
  },
  toSchedule() {
    let url = '/pages/weddingMan/personal/schedules/checkSchedules/checkSchedules'
    let {name , userId } = this.data

    if(userId){
      url = `${url}?userId=${userId}&name=${name}`
    }
    else {
      return
    }

    wx.navigateTo({
      url,
    });
  },
  showFunc(e) {
    console.log(e);
    if (e.currentTarget.dataset.type === '0') {
      if (!this.data.phone) {
        wx.showToast({
          title: '没有电话!',
          icon: 'none',
        });
      } else {
        wx.makePhoneCall({
          phoneNumber: this.data.phone,
          success: () => {
            ;
          },
        });
      }
    } else if (e.currentTarget.dataset.type === '1') {
      if (!this.data.wechat) {
        wx.showToast({
          title: '没有微信!',
          icon: 'none',
        });
      } else {
        wx.setClipboardData({
          data: this.data.wechat,
          success: () => {
            wx.showToast({
              title: '微信号复制成功!',
              icon: 'none',
            });
          },
          fail: () => {
            wx.showToast({
              title: '微信号复制失败!',
              icon: 'none',
            });
          },
        });
      }
    } else if (e.currentTarget.dataset.type === '2') {
      // 弹出身高、体重信息、生日信息
      this.setData({
        infoPopupVisible: true,
      });
    }
  },
  previewVideo() {
    wx.navigateTo({
      url: '/pages/weddingMan/personal/videoPlay/videoPlay?videoPath=' + this.data.homeCarouseList[0].mediaPath
    })
  }
});
